import Vue from "vue";
import Vuex from "vuex";

import { getUserInfoApi } from "@/api";
import { iscode } from "@/utils";
import { getCookie, clearCookies } from "@/utils/cookie";

Vue.use(Vuex);

const state = {
  //商城左侧导航
  mailTab: "",
  // 用户信息（将存放请求的用户数据）
  userInfo: {},
  equipment: {},
  wxCode: "",
  // 是否展示公告弹窗
  isShowNoticeDialog: false,
  // 是否隐藏首页公告
  isHiddenNotice: true,
  //是否不在显示购买提示
  isShowBuyTips: false,
  //优惠券id
  couponId: "",
  //支付信息
  payInfo: {}
};
const mutations = {
  // 关闭公告弹窗
  closeNoticeDialog(state) {
    state.isShowNoticeDialog = false;
    localStorage.setItem("phoneFirstLogin", JSON.stringify(false));
  },
  // 打开公告弹窗（仅在登录时调用）
  openNoticeDialog(state) {
    state.isShowNoticeDialog = true;
  },
  // 关闭首页公告
  closeHomeNotice(state) {
    state.isHiddenNotice = true;
    localStorage.setItem("pcFirstLogin", JSON.stringify(false));
  },
  // 打开首页公告
  openHomeNotice(state) {
    state.isHiddenNotice = false;
  },
  getWxCode(state, payload) {
    state.wxCode = payload;
  },
  //判断当前设备
  getEquipment(state, payload) {
    state.equipment = payload;
  },

  // ----- 用户信息相关 -----
  // 获取用户信息数据
  addUserInfo(state, payload) {
    state.userInfo = payload;
  },
  // 清空用户信息
  clearUserInfo(state) {
    state.userInfo = {};
    state.isShowBuyTips = false;
  },
  choseMailTab(state, payload) {
    state.mailTab = payload;
  },
  //购买提示
  neverTip(state) {
    state.isShowBuyTips = !state.isShowBuyTips;
  },

  setCouponId(state, payload) {
    state.couponId = payload;
  },

  setPayInfo(state, payload) {
    state.payInfo = payload;
  }
};
const actions = {
  // 获取用户信息
  async getUserInfo({ commit }) {
    let result = await getUserInfoApi({
      token: getCookie("token") || JSON.parse(window.localStorage.getItem("token"))
    });
    if (iscode(result)) {
      commit("addUserInfo", result.result);
    } else {
      localStorage.removeItem("isLogin");
      window.localStorage.removeItem("phoneFirstLogin");
      window.localStorage.removeItem("pcFirstLogin");
      window.localStorage.removeItem("isJump");
      window.localStorage.removeItem("token");
      clearCookies();
      commit("clearUserInfo");
    }
  }
};
const getters = {};

export default new Vuex.Store({
  state, // 状态
  mutations, // 包含多个更新state函数的对象
  actions, // 包含多个队形事件回调函数的对象
  getters // 包含多个getter计算属性函数的对象
});
